# -*- coding: utf-8 -*-
#这是把标准的data.json转化为csv的py脚本
import json
import csv
import sys
#把node节点所有孩子children的id也就是name抓取到一个字符串中（用空格分隔），返回这个字符串，用于生成csv
total=0
def getAllChildrenName(node):
	result=''
	if node.has_key('children'):
		for item in node['children']:
			result+=item['name']+' '
	else:
		return ''
	return result
def getAllChildrenIn(node):
	result=''
	if node.has_key('children'):
		for item in node['children']:			
			if item.has_key('children'):		
				result+=item['in']+' '	
			else:
				result+=item['out']+' '		
	else:
		return ''
	return result
def addRootToCsv(data,f):
	#生成标题行
	f.writerow(['name', 
		'totalnodelengthforroot','level', 
		'children','in','out'])	
	f.writerow([data['name'], 
		data['totalnodelength'], 
		data['level'],
		#getAllChildrenName(data),data['in'],data['out']])
		getAllChildrenIn(data),data['in'],data['out']])
	for item in data['children']:
		addNodeToCsv(item,f)
def addNodeToCsv(node,f):
	global total
	total+=1
	if node.has_key('in') and node['in']!="0":
		f.writerow([node['name'], 
			'', 
			node['level'],
			#getAllChildrenName(node),node['in'],node['out']])
			getAllChildrenIn(node),node['in'],node['out']])
	# else:
	# 	f.writerow([node['name'], 
	# 		'', 
	# 		node['level'],
	# 		#getAllChildrenName(node),0,node['out']])
	# 		getAllChildrenIn(node),0,node['out']])
	if node.has_key('children'):			
		for item in node['children']:
			addNodeToCsv(item,f)
	else:
		return
if __name__ == '__main__':
	print "convert start"
	if len(sys.argv)==3:
		f = open(sys.argv[1])
		data = json.load(f)
		print f
		f.close()
		f=csv.writer(open(sys.argv[2],'wb+'))
		addRootToCsv(data,f)
		print total
	else:
		f = open('data.json')
		data = json.load(f)
		print f
		f.close()
		f=csv.writer(open('data.csv','wb+'))
		addRootToCsv(data,f)
		print total
